package com.sright.bcard.cms.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.sright.bcard.common.service.share.mvcresolver.EnableLoginAuth;
import com.sright.bcard.common.service.share.utils.JWTUitls;
import com.sright.bcard.common.service.share.utils.JsonUtil;
import com.sright.common.response.SrightResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Map;

/**
 * Author: lumf
 * Date: 2020/8/17 3:59 PM
 */
@Slf4j
public class LoginIntercepter implements HandlerInterceptor  {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (needLogin(handler, request)) {
            String json = JSONObject.toJSONString(SrightResponse.defaultUnloginError());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);
            out.close();
            response.flushBuffer();
            return false;
        }
        return true;
    }

    private boolean needLogin(Object handler, HttpServletRequest request) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            EnableLoginAuth loginRequired = handlerMethod.getMethod().getAnnotation(EnableLoginAuth.class);
            // 如果方法上的注解为空 则获取类的注解
            if (loginRequired == null) {
                loginRequired = handlerMethod.getMethod().getDeclaringClass().getAnnotation(EnableLoginAuth.class);
            }
            // 如果标记了注解，则判断权限
            if (loginRequired != null) {
                // 查看是否已经登录
                String token = request.getHeader("Authorization");
                if (token == null || token.isEmpty()) {
                    return true;
                }
                log.info("auth:" + token);

                try {
                    Map<String, Object> claims = TokenVerifyUtil.verifyToken(token);
                    TokenInfo info = JsonUtil.json2bean((String) claims.get("info"), TokenInfo.class);
                    log.info("tokenInfo:" + JsonUtil.bean2json(info));
                    request.setAttribute("info", info);
                } catch (Exception e) {
                    return true;
                }
                return false;
            }
        }
        return false;
    }

    @Data
    public static class TokenInfo implements Serializable  {
        private Integer admin_id;

        private String admin_name;

        private String avatar;

        private Integer company_id;

        private Integer is_bind_wechat;

        private String env;
    }
}
